<template>
  <div>
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" label-width="68px" size="mini">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-form-item label="项目区域" prop="projectRegion">
            <el-select v-model="queryParams.projectRegion" clearable placeholder="请选择"
              @keyup.enter.native="handleQuery">
              <el-option v-for="dict in dict.type.cld_project_region" :key="dict.value" :label="dict.label"
                :value="parseInt(dict.value)"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="queryParams.projectName" clearable placeholder="请输入项目名称"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="讲师姓名" prop="staffName">
            <el-input v-model="queryParams.staffName" clearable placeholder="请输入" @keyup.enter.native="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="培训类型" prop="trainType">
            <el-select v-model="queryParams.trainType" clearable placeholder="请选择">
              <el-option v-for="item in trainerTypeOptions" :key="item.value" :label="item.label"
                :value="parseInt(item.value)"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="培训状态" prop="trainStatus">
            <el-select v-model="queryParams.trainStatus" clearable placeholder="请选择">
              <el-option v-for="item in trainStatusOptuons" :key="item.value" :label="item.label"
                :value="parseInt(item.value)"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label-width="10px">
            <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['cld:trainPlan:add']" icon="el-icon-plus" plain size="mini" type="primary"
          @click="handleAdd">新增培训计划
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="trainPlanList" border>
      <el-table-column align="center" label="项目区域" prop="projectRegion" width="120px;">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cld_project_region" :value="scope.row.projectRegion" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="项目名称" prop="projectName" width="200px;" />
      <el-table-column align="center" label="培训类型" prop="trainType" width="100px;">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.trainType == 1" >入职培训</el-tag>
          <el-tag v-if="scope.row.trainType == 2" >岗前培训</el-tag>
          <el-tag v-if="scope.row.trainType == 3" >专项培训</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="培训内容" prop="iecturerResult" />
      <el-table-column align="center" label="视频地址" prop="trainVideo" width="200px;" />
      <el-table-column align="center" label="开始时间" prop="startTime" width="100px;" />
      <el-table-column align="center" label="结束时间" prop="endTime" width="100px;" />
      <el-table-column align="center" label="奖励金额(元/人)" prop="money" width="120px;" />
      <el-table-column align="center" label="培训人数" prop="traineesNumber" width="80px;" />
      <el-table-column align="center" label="完成人数" prop="completedNumber" width="80px;" />
      <el-table-column align="center" label="客户查看" prop="isCustomerShow" width="100px;">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isCustomerShow == 1" type="success">是</el-tag>
          <el-tag v-if="scope.row.isCustomerShow == 0" type="info">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="培训员" prop="trainIecturerName" width="100px;" />
      <el-table-column align="center" label="审核员" prop="trainAuditorName" width="100px;" />
      <el-table-column align="center" label="培训状态" prop="trainStatus" width="100px;">
        <template slot-scope="scope">
          <dict-tag :options="trainStatusOptuons" :value="scope.row.trainStatus" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建人" prop="createName" width="120px;" />
      <el-table-column align="center" label="创建时间" prop="createTime" width="160px;">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="200px;">
        <template slot-scope="scope">
          <el-button v-hasPermi="['cld:trainPlan:receive']" icon="el-icon-edit" size="mini" type="text"
            @click="handleReceive(scope.row)">查看</el-button>
          <el-button v-hasPermi="['cld:trainPlan:edit']" icon="el-icon-edit" v-if="scope.row.trainStatus == 0"
            size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-hasPermi="['cld:trainPlan:remove']" icon="el-icon-delete" v-if="scope.row.trainStatus == 0"
            size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total"
      @pagination="getList" />

    <!-- 添加或修改培训讲师对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="60%">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="mini">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="培训项目" prop="projectId">
              <el-select filterable v-model="form.projectId" placeholder="请选择">
                <el-option v-for="item in projectOptions" :key="item.projectId" :label="item.projectName"
                  :value="item.projectId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="培训时间" prop="daterange">
              <el-date-picker v-model="form.daterange" end-placeholder="结束日期" range-separator="至"
                start-placeholder="开始日期" type="daterange"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="培训类型" prop="trainType">
              <el-select v-model="form.trainType" clearable placeholder="请选择">
                <el-option v-for="item in trainerTypeOptions" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="培训讲师" prop="trainIecturerName">
              <el-input v-model="form.trainIecturerName" placeholder="请选择培训讲师">
                <el-button slot="append" icon="el-icon-search" @click="selectedTrainerOpen = true">选择</el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审核员" prop="trainAuditorName">
              <el-input v-model="form.trainAuditorName" placeholder="请选择审核员">
                <el-button slot="append" icon="el-icon-search" @click="handleOpenAudit(0)">员工</el-button>
                <el-button slot="append" icon="el-icon-search" @click="handleOpenAudit(1)">系统用户</el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="奖金金额" prop="money">
              <el-input v-model="form.money" placeholder="请输入" type="number">
                <template slot="append">每人</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="视频地址" prop="trainVideo">
              <el-input v-model="form.trainVideo" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户查看" prop="isCustomerShow">
              <el-radio-group v-model="form.isCustomerShow">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button :disabled="!form.trainIecturerId" icon="el-icon-plus" plain size="mini" type="primary"
                @click="handleAddtrainees">添加受训员</el-button>
            </el-col>
          </el-row>
          <el-table v-loading="loading" :data="form.traineesList" @selection-change="handleSelectionChange" border>
            <el-table-column align="center" label="项目名称" prop="projectName" />
            <el-table-column align="center" label="员工姓名" prop="staffName" />
            <el-table-column align="center" label="职务" prop="jobName" />
            <el-table-column align="center" label="岗位" prop="projectPostName">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.cld_project_post" :value="scope.row.projectPostName" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="性别" prop="staffSex" />
            <el-table-column align="center" label="年龄">
              <template slot-scope="scope">
                {{ calculateAge(scope.row.staffIdcard) }}
              </template>
            </el-table-column>
            <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="handleDeleteStaff(scope.row)">移出</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="24">
            <el-form-item label="培训内容" prop="iecturerResult">
              <el-input v-model="form.iecturerResult" :rows="4" placeholder="请输入" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加培训讲师 -->
    <el-dialog :close-on-click-modal="false" :visible.sync="selectedTrainerOpen" append-to-body title="选择培训师"
      width="70%">
      <selected-trainer v-if="selectedTrainerOpen" @childInput="handleSelectedTrainer"></selected-trainer>
    </el-dialog>

    <!-- 审核员类型为员工 / 添加受训人 -->
    <el-dialog :close-on-click-modal="false" :visible.sync="selectedStaffOpen" append-to-body title="选择人员" width="70%">
      <selected-staff v-if="selectedStaffOpen" :isMultiple="isTrainees"
        :params="{ notStaffIds: notStaffIds, staffStatus: staffStatus }" type="trainer"
        @childInput="handleSelectedStaff" @multipleInput="handleStaffMultiple"></selected-staff>
      <div v-if="isTrainees" slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSelectedStaff">确 定</el-button>
        <el-button @click="cancelSelectedStaffOpen">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审核员类型为系统用户 -->
    <el-dialog :close-on-click-modal="false" :visible.sync="selectedUserOpen" append-to-body title="选择审核员" width="70%">
      <selected-user v-if="selectedUserOpen" @childInput="handleSelectedUser"></selected-user>
    </el-dialog>
  </div>
</template>

<script>
import { addTrainPlan, delTrainPlan, getTrainPlan, listTrainPlan, updateTrainPlan } from "@/api/cld/trainPlan";

import selectedTrainer from "./selectedTrainer.vue";
import selectedStaff from '../staff/selectedStaff.vue';
import selectedUser from "../../system/user/selectedUser.vue";
import { getList } from '@/api/cld/project'
import { trainerTypeOptions, trainStatusOptuons } from '@/assets/staticDict'

export default {
  name: "trainingProgram",
  dicts: ['cld_project_region', 'cld_project_post'],
  components: {
    selectedTrainer,
    selectedStaff,
    selectedUser
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 培训计划表格数据
      trainPlanList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectRegion: null,
        projectName: null,
        trainType: null,
        trainStatus: null,
        staffName: null,
      },
      // 表单参数
      form: {
        trainIecturerName: ''
      },
      // 表单校验
      rules: {
        daterange: [
          { required: true, message: "培训时间不能为空", trigger: "picker" }
        ],
        trainType: [
          { required: true, message: "培训类型不能为空", trigger: "blur" }
        ],
        money: [
          { required: true, message: "奖金金额不能为空", trigger: "blur" }
        ],
        iecturerResult: [
          { required: true, message: "培训内容不能为空", trigger: "blur" }
        ],
      },
      // 过滤受训人ids
      notStaffIds: [],
      // 多选临时存放
      temporaryList: [],
      // 是否打开添加受训人
      isTrainees: false,
      // 培训时间
      daterange: [],
      // 项目列表
      projectOptions: [],
      // 回访项目
      projectId: '',
      // 选择培训员
      selectedTrainerOpen: false,
      // 选择员工
      selectedStaffOpen: false,
      // 选择系统用户
      selectedUserOpen: false,
      // 培训类型
      trainerTypeOptions: trainerTypeOptions,
      // 培训状态
      trainStatusOptuons: trainStatusOptuons,
      // 选择员工状态
      staffStatus: 2
    };
  },
  created() {
    this.getList();
    this.handleGetProjectList();
  },
  methods: {
    /** 查询培训计划列表 */
    getList() {
      this.loading = true;
      listTrainPlan(this.queryParams).then((response) => {
        this.trainPlanList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        trainPlanId: null,
        projectId: null,
        daterange: null,
        trainIecturerId: null,
        startTime: null,
        endTime: null,
        money: null,
        trainType: null,
        isCustomerShow: 0,
        trainStatus: null,
        trainVideo: null,
        iecturerResult: null,
        trainAuditorId: null,
        trainAuditorType: null,
        traineesList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加培训计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getTrainPlan(row.trainPlanId).then((response) => {
        this.form = response.data;
        this.form.daterange = [this.form.startTime, this.form.endTime]
        this.daterange = [this.form.startTime, this.form.endTime]
        this.open = true;
        this.title = "修改培训计划";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.startTime = this.form.daterange[0];
          this.form.endTime = this.form.daterange[1];
          if (this.form.trainPlanId != null) {
            updateTrainPlan(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTrainPlan(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm(
          '是否确认删除培训计划编号为"' + row.trainPlanId + '"的数据项？'
        )
        .then(function () {
          return delTrainPlan(row.trainPlanId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
        });
    },
    // 查看培训计划人员
    handleReceive(row) {
      this.$router.push("/iecturer/receive/" + row.trainPlanId);
    },
    // 添加受训人
    handleAddtrainees() {
      if(this.form.trainType == 3){
        this.staffStatus = 2;
      }else{
        this.staffStatus = this.form.trainType;
      }
      // 获取已添加受训人ids 及培训讲师id
      this.notStaffIds = this.form.traineesList.map(item => item.staffId)
      this.notStaffIds.push(this.form.trainIecturerId);
      this.isTrainees = true;
      this.selectedStaffOpen = true;
    },
    // 选择审核员
    handleOpenAudit(type) {
      this.form.trainAuditorType = type;
      if (type == 0) {
        this.staffStatus = 2;
        this.selectedStaffOpen = true;
      } else {
        this.selectedUserOpen = true;
      }
    },
    // 取消选择受训人
    cancelSelectedStaffOpen() {
      this.selectedStaffOpen = false;
      this.isTrainees = false;
      this.temporaryList = [];
    },
    // 选择培训员回调
    handleSelectedTrainer(e) {
      this.form.trainIecturerName = e.staffName;
      this.form.trainIecturerId = e.staffId;
      this.selectedTrainerOpen = false;
    },
    // 选择员工回调
    handleSelectedStaff(e) {
      if (this.isTrainees) {
        this.temporaryList.forEach(item => {
          this.form.traineesList.push({
            ...item,
            trainPlanId: this.form.trainPlanId,
            recevieStatus: 0,
          })
        })
        this.isTrainees = false;
      } else {
        this.form.trainAuditorName = e.staffName;
        this.form.trainAuditorId = e.staffId;
        this.form.trainAuditorType = 0;
      }
      this.selectedStaffOpen = false;
    },
    // 选择系统用户回调
    handleSelectedUser(e) {
      this.form.trainAuditorName = e.nickName;
      this.form.trainAuditorId = e.userId;
      this.form.trainAuditorType = 1;
      this.selectedUserOpen = false;
    },
    // 选择受训人
    handleStaffMultiple(list) {
      this.temporaryList = list;
    },
    // 移除受训人
    handleDeleteStaff(row) {
      const index = this.form.traineesList.indexOf(row);
      if (index > -1) {
        this.form.traineesList.splice(index, 1);
      }
    },
    // 查询项目列表
    handleGetProjectList() {
      getList({
        projectStatus: 2
      }).then(res => {
        this.projectOptions = res.data;
      })
    },
  },
};
</script>
<style scoped>
.el-select {
  width: 100%;
}

.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
</style>
